//
//  ZPDetailInfoAndEvaluationVC.m
//  ZhenPin
//
//  Created by fei on 14-6-30.
//  Copyright (c) 2014年 zhenpin. All rights reserved.
//

#import "ZPDetailInfoAndEvaluationVC.h"
#import "ZPEvaluateCell.h"
#define BUTTON_TAG 400
@interface ZPDetailInfoAndEvaluationVC ()
{
    BOOL isLoadMore;
}
@end

@implementation ZPDetailInfoAndEvaluationVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
//    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated {
//    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    pageNum = 1;
    pageSize = 10;
    isLoadMore = NO;
    [self setNavBarButtonItem];
    evaluateDataArr = [[NSMutableArray alloc] initWithCapacity:0];
    productParameterArr = [[NSMutableArray alloc] initWithArray:_attriArray];
    hasSizeDetail = YES;
    
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/ServerConfig.plist"];
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    NSMutableString *urlString = [NSMutableString stringWithString:dataDic[@"zpProductSize"]];
    [urlString appendFormat:@"%@",_productId];
    
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL  URLWithString:urlString]];
    [_detailInfoWebView loadRequest:request];
    [_detailInfoWebView setScalesPageToFit:YES];
    _detailInfoTableView.delegate = self;
    tableFootView = [[EGORefreshTableFooterView alloc] initWithFrame:CGRectZero];
    tableFootView.delegate = self;
//    [_detailInfoTableView addSubview:tableFootView];
    
    
    tableFootView.hidden = YES;
    requestHud = [[MBProgressHUD alloc] initWithView:self.view];
    [requestHud setHidden:YES];
    [requestHud show:YES];
    [requestHud setMode:MBProgressHUDModeIndeterminate];
    [requestHud setLabelText:@"正在加载..."];
    
    [_detailInfoWebView addSubview:requestHud];
    [self.view bringSubviewToFront:requestHud];
    //请求商品sizetable
    [self requestProductSizeTable];
    [self setExtraCellLineHidden:_detailInfoTableView];
    
}



-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}
-(void)setRefreshViewFrame {
    int height = MAX(_detailInfoTableView.bounds.size.height, _detailInfoTableView.contentSize.height);
    tableFootView.frame =CGRectMake(0.0f, height, _detailInfoTableView.frame.size.width, _detailInfoTableView.bounds.size.height);
}
-(void)requestProductSizeTable {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *paraDict = @{@"productid": self.productId,
                               };
    MBProgressHUD *requestHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager GET:APIURL"products/getProductSizeTable.json" parameters:paraDict success:^(AFHTTPRequestOperation *ooperation,id resultObject) {
        NSString *str = resultObject[@"ProductSizeTable"];
        if ([str isEqual:[NSNull null]] || str == nil || str.length == 0) {
            hasSizeDetail = NO;
            _detailInfoWebView.hidden = YES;
        } else {
            _detailInfoWebView.hidden = NO;
            hasSizeDetail = YES;
        }
//        requestHUD.mode = MBProgressHUDModeText;
//        requestHUD.labelText = @"加载完成";
        [requestHUD hide:YES afterDelay:0.2];
        [self setSubTopView];
    }failure:^(AFHTTPRequestOperation *operation,NSError *error) {
        hasSizeDetail = NO;
        requestHUD.mode = MBProgressHUDModeText;
//        requestHUD.labelText = @"加载完成";
        [requestHUD hide:YES afterDelay:0.2];
        [self setSubTopView];
    }];
}
-(void)requestProductEvaluate {
    [requestHud setHidden:NO];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *paraDict = @{@"productId": _productId,
                               @"pagenumber": [NSString stringWithFormat:@"%d",pageNum],
                               @"pagesize" : [NSString stringWithFormat:@"%d",pageSize],
                               };

    [manager GET:APIURL"products/getEvaluate.json" parameters:paraDict success:^(AFHTTPRequestOperation *ooperation,id resultObject) {
        _totalEvaluateCount = [resultObject[@"totalCount"] intValue];
        
        UIButton *evaBtn = (UIButton *)[self.view viewWithTag:BUTTON_TAG + 2];
        if (evaBtn) {
            [evaBtn setTitle:[NSString stringWithFormat:@"评价详情(%d)",_totalEvaluateCount] forState:UIControlStateNormal];
            [evaBtn setTitle:[NSString stringWithFormat:@"评价详情(%d)",_totalEvaluateCount] forState:UIControlStateSelected];
        }
        
        [requestHud setHidden:YES];
        if (_totalEvaluateCount > 10 && _comfromType == 3) {
            tableFootView.hidden = NO;
        }
        if (!isLoadMore) {
            [evaluateDataArr removeAllObjects];
        }
        if (resultObject[@"result"]) {
            [evaluateDataArr addObjectsFromArray:resultObject[@"result"]];
        }
        if (evaluateDataArr.count == 0) {
            [self showNoDataViewWithKeyWord:@"此商品还没有被评论，赶紧去评论吧！"];
            return ;
        }
        
        
        [_detailInfoTableView reloadData];
        [self setRefreshViewFrame];
        [tableFootView egoRefreshScrollViewDataSourceDidFinishedLoading:_detailInfoTableView];
        
    }failure:^(AFHTTPRequestOperation *operation,NSError *error) {
        [requestHud setHidden:YES];
    }];
}

-(void)setSubTopView {
    if (hasSizeDetail) {    //尺码详情 yes 并且尺码详情存在
        
        NSArray *titleArray = [NSArray arrayWithObjects:@"产品参数",@"尺码详情",[NSString stringWithFormat:@"评价详情(%d)",_totalEvaluateCount], nil];
        for (int i = 0; i < titleArray.count; i ++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(10+99*i, 10, 100, 35);
            button.tag = BUTTON_TAG + i;
            [button setBackgroundColor:[UIColor whiteColor]];
            [button setTitleColor:RGB(51, 51, 51) forState:UIControlStateNormal];
            [button setTitle:[titleArray objectAtIndex:i] forState:UIControlStateNormal];
            [button setTitle:[titleArray objectAtIndex:i] forState:UIControlStateSelected];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [button addTarget:self action:@selector(selectItemBy:) forControlEvents:UIControlEventTouchUpInside];
            button.titleLabel.font = [UIFont systemFontOfSize:16];
            button.layer.borderColor = [UIColor blackColor].CGColor;
            button.layer.borderWidth = 1;
            if (_comfromType == 1 && i == 1) {
                selectedButton = button;
                selectedButton.selected = YES;
                [selectedButton setBackgroundColor:[UIColor blackColor]];
                _detailInfoWebView.hidden = NO;
                _detailInfoTableView.hidden = YES;
            } else if (i == 0 && _comfromType != 1) {
                selectedButton = button;
                selectedButton.selected = YES;
                [selectedButton setBackgroundColor:[UIColor blackColor]];
                _detailInfoTableView.hidden = NO;
                _detailInfoWebView.hidden = YES;
            }
            [_topBannerView addSubview:button];
        }
        
    } else {
        
        NSArray *titleArray = [NSArray arrayWithObjects:@"产品参数",[NSString stringWithFormat:@"评价详情(%d)",_totalEvaluateCount], nil];
        for (int i = 0; i < titleArray.count; i ++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(10+149*i, 10, 150, 35);
            
            [button setBackgroundColor:[UIColor whiteColor]];
            [button setTitleColor:RGB(51, 51, 51) forState:UIControlStateNormal];
            [button setTitle:[titleArray objectAtIndex:i] forState:UIControlStateNormal];
            [button setTitle:[titleArray objectAtIndex:i] forState:UIControlStateSelected];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [button addTarget:self action:@selector(selectItemBy:) forControlEvents:UIControlEventTouchUpInside];
            button.layer.borderColor = [UIColor blackColor].CGColor;
            button.layer.borderWidth = 1;
            button.titleLabel.font = [UIFont systemFontOfSize:16];
            if (i == 0) {
                selectedButton = button;
                selectedButton.selected = YES;
                [selectedButton setBackgroundColor:[UIColor blackColor]];
                button.tag = BUTTON_TAG + i;
                _comfromType = 2;
                _detailInfoTableView.hidden = NO;
                [_detailInfoTableView reloadData];
                _detailInfoWebView.hidden = YES;
            } else {
                button.tag = BUTTON_TAG + 2;
                
            }
            [_topBannerView addSubview:button];
        }
    }
}
-(void)selectItemBy:(UIButton *)button {
    if (selectedButton.tag == button.tag) {
        return;
    }
    [selectedButton setBackgroundColor:[UIColor whiteColor]];
    selectedButton.selected = NO;
    selectedButton = button;
    [selectedButton setBackgroundColor:[UIColor blackColor]];
    selectedButton.selected = YES;
    [self hideNoDataView];
    switch (button.tag) {
        case BUTTON_TAG:    //产品参数
            _comfromType = 2;
            _detailInfoTableView.hidden = NO;
            _detailInfoWebView.hidden = YES;
            tableFootView.hidden = YES;
            if (productParameterArr.count == 0) {
                [self showNoDataViewWithKeyWord:@"此商品没有产品参数！"];
            }
           
            [_detailInfoTableView reloadData];
            break;
        case BUTTON_TAG+1: //尺码详情
            _comfromType = 1;
            _detailInfoTableView.hidden = YES;
            _detailInfoWebView.hidden = NO;
            break;
        case BUTTON_TAG+2:  //评价详情
            _comfromType = 3;
            tableFootView = NO;
            _detailInfoWebView.hidden = YES;
            _detailInfoTableView.hidden = NO;
            isLoadMore = NO;
            if (evaluateDataArr.count == 0) {
                [self requestProductEvaluate];
            }
//            [self requestProductEvaluate];
            
            [_detailInfoTableView reloadData];
            break;
            
        default:
            break;
    }
}
-(void)setNavBarButtonItem {
    self.title = @"产品参数&评价";
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}
    
-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -- UITableView delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_comfromType == 2) {
        return productParameterArr.count;
    } else if (_comfromType == 3) {
        if (evaluateDataArr.count <= _totalEvaluateCount && evaluateDataArr.count != 0) {
            return evaluateDataArr.count + 1;
        }
        return evaluateDataArr.count;
    }
    return 0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_comfromType == 2) {
        
        return 44;
    } else if (_comfromType == 3) {
        if (evaluateDataArr.count <= indexPath.row) {
            return 44;
        }
        NSDictionary *dict = [evaluateDataArr objectAtIndex:indexPath.row];
        ZPEvaluateCell *cell = [[ZPEvaluateCell alloc] initWithStyle:UITableViewCellStyleDefault justForHeightWithSourceDict:dict];
        
        return cell.frame.size.height;
    }
    return 44;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (_comfromType == 2) {    //产品参数
        
        NSDictionary *dict = [productParameterArr objectAtIndex:indexPath.row];
        cell = [self createCellWithDict:dict];
    } else if (_comfromType == 3) { //评论
        if (evaluateDataArr.count <= indexPath.row ) {//最后一行
            if (evaluateDataArr.count < _totalEvaluateCount && indexPath.row != 0) {
                
                UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
                UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.frame = CGRectMake(20, 5, 30, 30);
                [act startAnimating];
                [cell.contentView addSubview:act];
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 200, 30)];
                label.font = [UIFont systemFontOfSize:14];
                label.textColor = RGB(51, 51, 51);
                label.text = @"正在加载更多评论...";
                [cell.contentView addSubview:label];
                [self reloadMoreData];
                return cell;
            } else if (evaluateDataArr.count == _totalEvaluateCount) {
                UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
                cell.textLabel.font = [UIFont systemFontOfSize:14];
                cell.textLabel.textColor = [UIColor lightGrayColor];
                cell.textLabel.text = @"已加载完所有评论数据 ...";
                
                return cell;
            }
        }
        NSDictionary *dict = [evaluateDataArr objectAtIndex:indexPath.row];
        
        ZPEvaluateCell *cell = (ZPEvaluateCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"evaluateCell"];
        if (cell) {
            cell = nil;
        }
        cell = [[ZPEvaluateCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"evaluateCell" WithSourceDict:dict];
        cell.delegate_image = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
-(UITableViewCell *)createCellWithDict:(NSDictionary *)dict {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"parameterCell"];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 120, cell.contentView.frame.size.height)];
    titleLabel.numberOfLines = 0;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:13];
    titleLabel.backgroundColor = [UIColor whiteColor];
    titleLabel.text = [NSString stringWithFormat:@"%@:",dict[@"attrname"]];
    [cell.contentView addSubview:titleLabel];
    
    UILabel *infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(122, 0, 188, cell.contentView.frame.size.height)];
    infoLabel.numberOfLines = 3;
    infoLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    infoLabel.textAlignment = NSTextAlignmentCenter;
    infoLabel.font = [UIFont fontWithName:@"Heiti SC" size:13];
    infoLabel.backgroundColor = [UIColor darkGrayColor];
    infoLabel.backgroundColor = [UIColor whiteColor];
    infoLabel.text = [NSString stringWithFormat:@"%@",dict[@"attrvalues"]];
    [cell.contentView addSubview:infoLabel];
    
    
    return cell;
}

#pragma mark -- EvaluateDelegate
-(void)evaluateCellDidSelectItemAtIndex:(NSInteger)index toViewController:(UIViewController *)targetVC {
    [self.navigationController pushViewController:targetVC animated:YES];
}

#pragma mark -- UIScrollView delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (_comfromType == 3) {
        [tableFootView egoRefreshScrollViewDidScroll:scrollView];
//        if (scrollView.contentSize.height) {
//            
//        }
    }
    
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (_comfromType == 3) {
        [tableFootView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
}

#pragma mark -- EGOARefreshTableFooterView delegate
-(void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView *)view {
//    [self reloadMoreData];
}
-(BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView *)view {
    if (_comfromType == 3) {
        return YES;
    }
    return NO;
}

-(NSDate *)egoRefreshTableFooterDataSourceLastUpdated:(EGORefreshTableFooterView *)view {
    return [NSDate date];
}

#pragma mark -- UIWebView delegate 
-(void)webViewDidFinishLoad:(UIWebView *)webView {
    [requestHud setHidden:YES];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [requestHud setHidden:YES];
}

-(void)reloadMoreData {
    
    if (pageNum * pageSize < _totalEvaluateCount) {
        pageNum += 1;
        isLoadMore = YES;
        [self requestProductEvaluate];
    } else {
        [tableFootView egoRefreshScrollViewDataSourceDidFinishedLoading:_detailInfoTableView];
    }
}


-(void)navigationBackClicked {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)showNoDataViewWithKeyWord:(NSString *)key {
    
    NSString *str = [NSString stringWithFormat:@"%@",key];
    NSMutableAttributedString *textStr = [[NSMutableAttributedString alloc] initWithString:str];
    
    if (noDataView) {
        UILabel *label = (UILabel*)[noDataView viewWithTag:800];
        label.attributedText = textStr;
        noDataView.hidden = NO;
        [_detailInfoTableView setTableFooterView:noDataView];
    } else {
        
        noDataView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, _detailInfoTableView.frame.size.height)];
//        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];
//        imageView.center = CGPointMake(noDataView.frame.size.width/2, (noDataView.frame.size.height-140)/2+45);
//        imageView.image = [UIImage imageNamed:@"noGoods"];
//        [noDataView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, (noDataView.frame.size.height-140)/2, 320, 30)];
        label.textColor = RGB(51, 51, 51);
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = 800;
        label.attributedText = textStr;
        [noDataView addSubview:label];
        noDataView.backgroundColor = [UIColor whiteColor];
        [_detailInfoTableView setTableFooterView:noDataView];
    }
}
-(void)hideNoDataView {
    if (noDataView) {
        noDataView.hidden = YES;
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
